package cn.itcast.web.controller;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    /*
        作用：判断登录，跳转到后台首页  home/main
    */
    @RequestMapping("/login")
    public String login(String email,String password){
        /*if (email==null||email.equals("")||password==null||password.equals(""))*/
        if(StringUtils.isEmpty(email)|| StringUtils.isEmpty(password)){
            request.setAttribute("error","用户或者密码不能为空");
            return "forward:/login.jsp";
        }

        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(email,password);
            //4. 使用subject对象把token发出登陆认证请求,其实本质上就是token传递给了realm
            subject.login(token);

            //如果登录成功，subject就会存储一些登陆的标记
            User user = (User) subject.getPrincipal();
            //登录成功将用户信息存储在session中,方便自己使用
            session.setAttribute("loginUser",user);
            //立马加载用户所拥有的模块
            List<Module> userModule = moduleService.findModuleByUser(user);
            session.setAttribute("modules",userModule);
            return "home/main";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            request.setAttribute("error","用户不存在");
            return "forward:/login.jsp";
        } catch (IncorrectCredentialsException e){
            request.setAttribute("error","密码错误");
            return "forward:/login.jsp";
        }

    }

    //logout.do  该方法任务：清除保存的用户，退出登录
    @RequestMapping("/logout")
    public String logout(){

        //1. 先使用shiro的方法销毁shiro的登录成功标记
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); //销毁shiro在session的标记，然后你才能摧毁session

        session.invalidate();

        return "redirect:/login.jsp";
    }

    //该方法任务： 让后台首页的内容区域去到  home/home.jsp
    @RequestMapping("/home")
    public String home(){
        return "home/home";
    }
}
